﻿using System;
using System.Web.Caching;

namespace Presentation.Web.Core.CDN
{
    public abstract class FileDependencyCacheBase<T>
    {
        protected FileDependencyCacheBase() { }

        protected virtual T GetItem(string key)
        {
            Cache cache = this.GetCache();
            string internalKey = this.GetCacheKey(key);
            object value = cache.Get(internalKey);
            if (value == null)
            {
                value = this.LoadItem(key);
                string dependencyPath = this.GetDependencyPath(key);
                if (String.IsNullOrEmpty(dependencyPath))
                {
                    cache.Insert(internalKey, value);
                }
                else
                {
                    cache.Insert(internalKey, value, new CacheDependency(dependencyPath));
                }
            }
            return (T)value;
        }

        protected virtual T Remove(string key)
        {
            string internalKey = this.GetCacheKey(key);
            return (T)this.GetCache().Remove(internalKey);
        }

        protected virtual string GetCacheKey(string key)
        {
            return this.GetType().ToString() + "_" + key;
        }

        protected virtual Cache GetCache()
        {
            return System.Web.HttpRuntime.Cache;
        }

        protected abstract T LoadItem(string key);

        protected abstract string GetDependencyPath(string key);
    }
}
